package middlewares

import (
	"longmen/server/config/global"
	"time"

	"longmen/server/pkg/common/api_models"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_guess"
	"longmen/server/pkg/db/mysql/models/models_main"

	"github.com/labstack/echo/v4"
	"gorm.io/gorm"
)

func ActionStep(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		d := c.Request().Header.Get("device-info")
		global.GetRds().Set(_const.ACTION_GUESS_TO_LOGIN+d, 1, 3600*time.Second)
		return next(c)
	}
}

func GuessToLog(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		d := c.Request().Header.Get("device-info")
		ret := global.GetRds().Get(_const.ACTION_GUESS_TO_LOGIN + d).Val()
		_log := global.GetRds().Get(_const.ACTION_GUESS_TO_LOGIN + d + "_1").Val()
		if ret != "" && _log != "1" {
			global.Guess().Model(&models_guess.GuessToLogged{}).Create(&models_guess.GuessToLogged{
				DeviceInfo: d,
				Datetime:   time.Now(),
				LiveID:     ret,
			})
			global.GetRds().Set(_const.ACTION_GUESS_TO_LOGIN+d+"_1", 1, 7200*time.Second)
		}
		return next(c)
	}
}

func Analytics(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {

		var r api_models.ActionReq
		var action = 1
		util.Json2Struct(c.Get("body").(string), &r)
		if r.Desc == "" {
			return next(c)
		}

		var d models_main.DialogConfig
		err := global.GetR().Model(&d).Where("status=1").First(&d).Error
		if err != nil {
			return err
		}
		var _check int64
		global.GetR().Model(&models_main.User{}).Where("account=? or mobile=?", r.Account, r.Account).Count(&_check)
		if _check > 0 {
			action = 1
			// 弹窗登录
			global.GetX().Model(&d).Where("id=?", d.ID).Update("login_count", gorm.Expr("login_count+1"))
		} else {
			action = 2
			// 弹窗登录
			global.GetX().Model(&d).Where("id=?", d.ID).Update("reg_count", gorm.Expr("reg_count+1"))
		}
		global.GetX().Model(&models_main.Analytics{}).Create(&models_main.Analytics{
			Action:   int32(action),
			AnchorID: r.AnchorID,
			User:     r.Account,
			LiveID:   r.LiveID,
			Desc:     r.Desc,
		})

		return next(c)
	}
}
